import { v4 as uuidv4 } from 'uuid';
import { STORAGE_KEYS, ERROR_MESSAGES } from './constants';

/**
 * 生成唯一用户ID
 */
export const generateUserId = (): string => {
  let userId = localStorage.getItem(STORAGE_KEYS.USER_ID);
  if (!userId) {
    userId = uuidv4();
    localStorage.setItem(STORAGE_KEYS.USER_ID, userId);
  }
  return userId;
};

/**
 * 获取用户ID
 */
export const getUserId = (): string => {
  return localStorage.getItem(STORAGE_KEYS.USER_ID) || generateUserId();
};

/**
 * 复制文本到剪贴板
 */
export const copyToClipboard = async (text: string): Promise<boolean> => {
  try {
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(text);
      return true;
    } else {
      // 降级方案
      const textArea = document.createElement('textarea');
      textArea.value = text;
      textArea.style.position = 'fixed';
      textArea.style.left = '-999999px';
      textArea.style.top = '-999999px';
      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();
      const result = document.execCommand('copy');
      textArea.remove();
      return result;
    }
  } catch (error) {
    console.error('复制到剪贴板失败:', error);
    return false;
  }
};

/**
 * 格式化时间
 */
export const formatTime = (seconds: number): string => {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const secs = Math.floor(seconds % 60);

  if (hours > 0) {
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  }
  return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
};

/**
 * 格式化文件大小
 */
export const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 Bytes';
  
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

/**
 * 检查浏览器是否支持WebRTC
 */
export const isWebRTCSupported = (): boolean => {
  return !!(window.RTCPeerConnection && navigator.mediaDevices && navigator.mediaDevices.getUserMedia);
};

/**
 * 检查是否为移动设备
 */
export const isMobileDevice = (): boolean => {
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
};

/**
 * 获取浏览器信息
 */
export const getBrowserInfo = (): { name: string; version: string } => {
  const userAgent = navigator.userAgent;
  let browserName = 'Unknown';
  let browserVersion = 'Unknown';

  if (userAgent.indexOf('Chrome') > -1) {
    browserName = 'Chrome';
    browserVersion = userAgent.match(/Chrome\/(\d+)/)![1];
  } else if (userAgent.indexOf('Firefox') > -1) {
    browserName = 'Firefox';
    browserVersion = userAgent.match(/Firefox\/(\d+)/)![1];
  } else if (userAgent.indexOf('Safari') > -1) {
    browserName = 'Safari';
    browserVersion = userAgent.match(/Version\/(\d+)/)![1];
  } else if (userAgent.indexOf('Edge') > -1) {
    browserName = 'Edge';
    browserVersion = userAgent.match(/Edge\/(\d+)/)![1];
  }

  return { name: browserName, version: browserVersion };
};

/**
 * 防抖函数
 */
export const debounce = <T extends (...args: any[]) => any>(
  func: T,
  wait: number
): ((...args: Parameters<T>) => void) => {
  let timeout: NodeJS.Timeout;
  return (...args: Parameters<T>) => {
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(null, args), wait);
  };
};

/**
 * 节流函数
 */
export const throttle = <T extends (...args: any[]) => any>(
  func: T,
  limit: number
): ((...args: Parameters<T>) => void) => {
  let inThrottle: boolean;
  return (...args: Parameters<T>) => {
    if (!inThrottle) {
      func.apply(null, args);
      inThrottle = true;
      setTimeout(() => (inThrottle = false), limit);
    }
  };
};

/**
 * 重试函数
 */
export const retry = async <T>(
  fn: () => Promise<T>,
  maxAttempts: number = 3,
  delay: number = 1000
): Promise<T> => {
  let lastError: Error;
  
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    try {
      return await fn();
    } catch (error) {
      lastError = error as Error;
      if (attempt === maxAttempts) {
        throw lastError;
      }
      await new Promise(resolve => setTimeout(resolve, delay * attempt));
    }
  }
  
  throw lastError!;
};

/**
 * 验证房间ID格式
 */
export const isValidRoomId = (roomId: string): boolean => {
  return /^[a-zA-Z0-9-_]{6,36}$/.test(roomId);
};

/**
 * 生成房间链接
 */
export const generateRoomUrl = (roomId: string): string => {
  return `${window.location.origin}/room/${roomId}`;
};

/**
 * 从URL中提取房间ID
 */
export const extractRoomIdFromUrl = (url: string): string | null => {
  const match = url.match(/\/room\/([a-zA-Z0-9-_]+)/);
  return match ? match[1] : null;
};

/**
 * 获取错误消息
 */
export const getErrorMessage = (error: any): string => {
  if (typeof error === 'string') {
    return error;
  }
  
  if (error?.message) {
    return error.message;
  }
  
  if (error?.name) {
    switch (error.name) {
      case 'NotAllowedError':
        return ERROR_MESSAGES.CAMERA_PERMISSION_DENIED;
      case 'NotFoundError':
        return ERROR_MESSAGES.MEDIA_DEVICE_NOT_FOUND;
      case 'NotSupportedError':
        return ERROR_MESSAGES.WEBRTC_NOT_SUPPORTED;
      default:
        return ERROR_MESSAGES.UNKNOWN_ERROR;
    }
  }
  
  return ERROR_MESSAGES.UNKNOWN_ERROR;
};

/**
 * 计算网络质量
 */
export const calculateNetworkQuality = (stats: {
  packetsLost: number;
  packetsReceived: number;
  roundTripTime: number;
}): 'good' | 'fair' | 'poor' => {
  const packetLossRate = stats.packetsLost / (stats.packetsLost + stats.packetsReceived);
  
  if (packetLossRate < 0.02 && stats.roundTripTime < 150) {
    return 'good';
  } else if (packetLossRate < 0.05 && stats.roundTripTime < 300) {
    return 'fair';
  } else {
    return 'poor';
  }
};

/**
 * 保存最近访问的房间
 */
export const saveRecentRoom = (roomId: string): void => {
  try {
    const recentRooms = getRecentRooms();
    const updatedRooms = [roomId, ...recentRooms.filter(id => id !== roomId)].slice(0, 5);
    localStorage.setItem(STORAGE_KEYS.RECENT_ROOMS, JSON.stringify(updatedRooms));
  } catch (error) {
    console.error('保存最近房间失败:', error);
  }
};

/**
 * 获取最近访问的房间
 */
export const getRecentRooms = (): string[] => {
  try {
    const stored = localStorage.getItem(STORAGE_KEYS.RECENT_ROOMS);
    return stored ? JSON.parse(stored) : [];
  } catch (error) {
    console.error('获取最近房间失败:', error);
    return [];
  }
};

/**
 * 清理最近访问的房间
 */
export const clearRecentRooms = (): void => {
  try {
    localStorage.removeItem(STORAGE_KEYS.RECENT_ROOMS);
  } catch (error) {
    console.error('清理最近房间失败:', error);
  }
};